package ${basepackage}.framework.service;

import java.io.Serializable;
import java.util.Objects;

import javax.annotation.PostConstruct;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.ncs.secon.toolkit.jse2e.SecureEncryptTools;
import com.ncs.secon.toolkit.jse2e.commons.ToolkitException;

public class ShiroRealm extends AuthorizingRealm {


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if(principals == null){
			throw new AuthorizationException("PrincipalCollection method argement canot be null");
		}
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
/*		User user = userService.getUserByLoginName(shiroUser.loginName);
		
		info.addRoles(user.getRoleList());
		
		System.out.println("user.getLoginId() = " + user.getLoginId());
		System.out.println("user.getRoles() = " + info.getRoles());
*/
		
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		
/*		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		User user = userService.getUserByLoginName(token.getUsername());
		if(user == null){
			System.out.println(" user is empty for " + token.getUsername());
			throw new AuthorizationException("User " + token.getUsername() + " cannot login");
		}
		SimpleAuthenticationInfo info = null;
		if(user.getLoginId().equals(token.getUsername()))
		{
			info = new SimpleAuthenticationInfo(new ShiroUser(user.getId(),user.getLoginId(), user.getUserName()),RSAUtils.decode(user.getPassword()),user.getLoginId());
			setSession(AppConstant.SESSION_USER_ID, user.getLoginId());
			
		}
		return info;
*/	
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		SimpleAuthenticationInfo info = null;
		
		info = new SimpleAuthenticationInfo(new ShiroUser(1,"admin", "admin"),"admin","admin");
			
		
		return info;
	
	}
	
	 @PostConstruct  
	    public void initCredentialsMatcher() {  
	        setCredentialsMatcher(new CustomCredentialsMatcher());  
	  
	    }  
	 
	 public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
			@Override  
	        public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {  
	            UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
	  
	            String password = String.valueOf(token.getPassword());
	            System.out.println("password in Realm is " + password);
	            System.out.println("password in info is " + String.valueOf(info.getCredentials()));
	            System.out.println("info.getCredentials " + String.valueOf(token.getPassword()));
	            try {
	    			password = SecureEncryptTools.decryptPass(password);
	    		} catch (ToolkitException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	            
	            System.out.println("password after decrypt is " + password);
	            //将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false  
	            boolean result = equals(password, String.valueOf(info.getCredentials()));
	            System.out.println("The match result is " + result);
	            return result;
	        }  
		}
	

	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public int id;
		public String loginName;
		public String name;


		public ShiroUser(int id,String loginName, String name) {
			this.id = id;
			this.loginName = loginName;
			this.name = name;
		}

		public String getName() {
			return name;
		}
		
		

		public int getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return loginName;
		}

		/**
		 * 重载hashCode,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(loginName);
		}

		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			ShiroUser other = (ShiroUser) obj;
			if (loginName == null) {
				if (other.loginName != null) {
					return false;
				}
			} else if (!loginName.equals(other.loginName)) {
				return false;
			}
			return true;
		}
	}
}
